#!/usr/bin/env bash


### Create a database backup.
###
### Usage:
###     $ docker-compose -f <environment>.yml (exec |run --rm) mysql backup


set -o errexit
set -o pipefail
set -o nounset


working_dir="$(dirname ${0})"
source "${working_dir}/_sourced/constants.sh"
source "${working_dir}/_sourced/messages.sh"


message_welcome "Backing up the '${MYSQL_DATABASE}' database..."


if [[ "${MYSQL_USER}" == "root" ]]; then
    message_error "Backing up as 'root' user is not supported. Assign 'MYSQL_USER' env with another one and try again."
    exit 1
fi

export MYSQL_TCP_PORT="${MYSQL_PORT}"
export MYSQL_HOST="${MYSQL_HOST}"

backup_filename="${BACKUP_FILE_PREFIX}_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz"
backup_file_path="${BACKUP_DIR_PATH}/${backup_filename}"


mysqldump --no-tablespaces --user=${MYSQL_USER} --password=${MYSQL_PASSWORD} --port=${MYSQL_PORT} ${MYSQL_DATABASE} | gzip > "${backup_file_path}"



message_success "'${MYSQL_DATABASE}' database backup '${backup_filename}' has been created and placed in '${BACKUP_DIR_PATH}'."
